package com.sp.shoppingplatform.controller;

import com.sp.shoppingplatform.common.result.Result;
import com.sp.shoppingplatform.dto.UserLoginDTO;
import com.sp.shoppingplatform.dto.UserRegisterDTO;
import com.sp.shoppingplatform.entity.User;
import com.sp.shoppingplatform.service.UserService;
import com.sp.shoppingplatform.util.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        return Result.success(userService.register(user));
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        User user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        String token = jwtUtil.generateToken(user.getUsername());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        user.setPassword(null);
        result.put("user", user);
        
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<User> getUserInfo(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            user.setPassword(null);
        }
        return Result.success(user);
    }

    @PutMapping
    public Result<Boolean> updateUser(@RequestBody User user) {
        return Result.success(userService.updateUser(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUser(@PathVariable Long id) {
        return Result.success(userService.deleteUser(id));
    }

    @GetMapping
    public Result<List<User>> getUserList() {
        List<User> users = userService.getUserList();
        // 清除所有用户的密码信息
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }
}
